package com.atguigu.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.alipay.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author : Jungle
 * @Description : 接收支付宝的消息
 *
 * 处理器，还需要响应数据
 */
@Slf4j
@RestController
public class OrderPayedListener {
    @Autowired
    private OrderService orderService;
    @Autowired
    private AlipayTemplate alipayTemplate;
    /**
     * 只要我们收到了支付宝给我们发的异步通知，告诉我们订单支付成功， 返回"success"，支付宝就再也不通知
     * 将支付宝返回调通知的参数封装在PayAsyncVo
     */
    @PostMapping("/payed/notify")
    public String handleAlipayed(PayAsyncVo vo, HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {


        //Map<String, String[]> parameterMap = request.getParameterMap();
        //for (String key : parameterMap.keySet()) {
        //    String value = request.getParameter(key);
        //    log.info("参数名==>{}，参数值==>{}",key,value);
        //}
        //log.info("支付宝通知到位了，数据==>{}", JSON.toJSONString(parameterMap));
        //验签
        if (isSignVerified(request)){
            //签名验证成功
            System.out.println("签名验证成功======");
            String result = orderService.handlePayResult(vo);
            return result;
        }else {
            //签名验证失败，返回不是"success"都可以
            System.out.println("签名验证失败======");
            return "error";
        }
    }



    /**
     * 1、获取支付宝POST过来反馈信息 验签
     */
    private boolean isSignVerified(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用 ,这个要注释掉，不然验证不通过
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        return AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type());
    }
}
